package com.jack.lib.core.utils;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;

import java.util.List;
import java.util.Stack;

/**
 * 作者: jack(黄冲)
 * 邮箱: 907755845@qq.com
 * create on 2017/12/18
 */

public class AppManager {

    private static Stack<Activity> activityStack;
    private static Stack<Service> serivceStack;

    private AppManager() {
    }

    /**
     * 单一实例
     */
    public static AppManager getInstance() {
        return SingleApp.INSTANCE;
    }


    /**
     * 判断Activity是不是活的
     * @param cls
     * @return
     */
    public boolean isAlive(Class<?> cls) {
        if (activityStack != null){
            for (Activity activity : activityStack) {
                if (activity.getClass().equals(cls)) {
                    return true;
                }
            }
        }
        return false;
    }

    public static class SingleApp {
        private static AppManager INSTANCE = new AppManager();
    }

    /**
     * 添加Activity到堆栈
     */
    public void addActivity(Activity activity) {
        if (activityStack == null) {
            activityStack = new Stack<>();
        }
        activityStack.add(activity);
    }


    /**
     * 移除Activity
     */
    public void removeActivity(Activity activity) {
        activityStack.remove(activity);
    }

    /**
     * 获取指定的Activity
     */
    public <T extends Activity> T getActivity(Class<T> cls) {
        if (activityStack != null)
            for (Activity activity : activityStack) {
                if (activity.getClass().equals(cls)) {
                    return (T)activity;
                }
            }
        return null;
    }

    public Activity getActivity(String clsName) {
        if (activityStack != null)
            for (Activity activity : activityStack) {
                if (activity.getClass().getName().equals(clsName)) {
                    return activity;
                }
            }
        return null;
    }


    /**
     * 获取当前显示Activity（堆栈中最后一个传入的activity）
     */
    public Activity getLastActivity() {
        return activityStack.lastElement();
    }

    /**
     * 获取所有Activity
     */
    public Stack<Activity> getAllActivity() {
        return activityStack == null ? new Stack<>() : activityStack;
    }


    /**
     * 结束指定的Activity
     */
    public void finishActivity(Activity activity) {
        if (activity != null) {
            if (!activity.isFinishing()) {
                activity.finish();
            }
        }
    }

    /**
     * 结束指定类名的Activity
     */
    public void finishActivity(Class cls) {
        for (Activity activity : activityStack) {
            if (activity.getClass().equals(cls)) {
                finishActivity(activity);
                break;
            }
        }
    }

    /**
     * 结束除当前传入以外所有Activity
     */
    public void finishOthersActivity(Class cls) {
        if (activityStack != null)
            for (Activity activity : activityStack) {
                if (!activity.getClass().equals(cls)) {
                    activity.finish();
                }
            }
    }

    /**
     * 结束所有Activity
     */
    public void finishAllActivity() {
        if (activityStack != null){
            for (Activity activity : activityStack) {
                activity.finish();
            }
            activityStack.clear();

        }

    }


    /**
     * 添加Service到堆栈
     */
    public void addService(Service service) {
        if (serivceStack == null) {
            serivceStack = new Stack<>();
        }
        serivceStack.add(service);
    }

    /**
     * 移除Service
     */
    public void removeService(Service service) {
        serivceStack.remove(service);
    }


    /**
     * 获取指定的Serivce
     */
    public <T> T getSerivce(Class<?> cls) {
        if (serivceStack != null)
            for (Service service : serivceStack) {
                if (service.getClass().equals(cls)) {
                    return (T) service;
                }
            }
        return null;
    }


    /**
     * 获取堆栈中最后一个传入的Service
     */
    public Service getLastService() {
        return serivceStack.lastElement();
    }

    /**
     * 结束指定的Service
     */
    public void stopService(Service service) {
        if (service != null) {
            service.stopSelf();
        }
    }

    /**
     * 结束指定类名的Service
     */
    public void stopService(Class cla) {
        for (Service service : serivceStack) {
            if (service.getClass().equals(cla)) {
                service.stopSelf();
                return;
            }
        }
    }

    /**
     * 结束所有Activity
     */
    public void stopAllService() {
        if (serivceStack != null){
            for (Service service : serivceStack) {
                service.stopSelf();
            }
            serivceStack.clear();
        }
    }

    /**
     * 获取所有Service
     */
    public Stack<Service> getAllActivitySerivce() {
        return serivceStack;
    }


    /**
     * time    : 2019/4/3 01:38
     * desc    : 获取指定的Fragment
     * versions: 1.0
     */
    public <T extends Fragment, V extends FragmentActivity> T getFragment(Class<V> activityClass, Class<T> fragmentClass) {
        if (activityClass == null) {
            throw new NoSuchFieldError("Activity Class不能为空");
        }
        FragmentActivity activity = getInstance().getActivity(activityClass);
        if (activity == null) {
            return null;
        }
        List<Fragment> fragments = activity.getSupportFragmentManager().getFragments();
        if (fragments == null || fragments.size() == 0){
            return null;
        }
        for (Fragment fragment : fragments) {
            if (fragment.getClass() == fragmentClass) {
                return (T) fragment;
            }
        }
        return null;
    }





    /**
     * 退出应用程序
     */
    public void AppExit() {
        try {
            finishAllActivity();
            stopAllService();
            android.os.Process.killProcess(android.os.Process.myPid());// 杀死该应用进程
            System.exit(0);
        } catch (Exception e) {
        }
    }

    public void reStartAppDelay(Context context, long delay){
        Intent intent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
        PendingIntent restartIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        AlarmManager mgr = ((AlarmManager) context.getSystemService(Context.ALARM_SERVICE));
        if (Build.VERSION.SDK_INT >= 23) {// 6.0及以上
            mgr.set(AlarmManager.RTC, System.currentTimeMillis() + delay, restartIntent);// 1秒钟后重启应用
        } else if (Build.VERSION.SDK_INT >= 19) {// 4.4及以上
            mgr.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + delay, restartIntent);
        }
    }


}